package com.liefox.servicemsm.controller;

import com.liefox.commonutils.R;
import com.liefox.servicemsm.service.MsmService;
import com.liefox.servicemsm.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @Author zjh
 * @Date 2021/7/19 下午 5:26
 **/
@Api(description = "邮箱验证码")
@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("send/{email}")
    public R sendMsm(@PathVariable String email) {

        //从redis中获取验证码，如果获取到就直接返回
        final String code = redisTemplate.opsForValue().get(email);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //4位验证码
        final String fourBitRandom = RandomUtil.getFourBitRandom();

        Boolean res = msmService.sendMsm(email, fourBitRandom);

        if (res) {
            //如果发送成功，把发送成功的验证码放到redis里面,并设置3分钟的过期时间
            redisTemplate.opsForValue().set(email, fourBitRandom, 3, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("邮箱验证码发送失败！");
        }

    }
}
